package com.ngkj.zmfptwebsocket.task;

import com.ngkj.zmfptCommon.common.bean.ChatMessage;
import com.ngkj.zmfptwebsocket.chatModule.service.write.ChatMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * @author ChenHN
 * @since 2021/11/18 creation
 **/
@Slf4j
@Component
public class WsTimingTask {

    @Resource
    private RedisTemplate<String, ChatMessage> redisTemplate;

    @Resource
    private ChatMessageService chatMessageService;

    /**
     * 每隔6小时 将聊天记录从redis 持久化到mysql
     */
    @Scheduled(fixedRate = 1000*30)
    public void saveWsTask(){
        log.info("持久化聊天记录！");
        Set<String> keys = redisTemplate.keys("websocket_save*");
        //遍历所有还未存储到mysql的节点
        for (String key : keys) {
            List<ChatMessage> range = redisTemplate.opsForList().range(key, 0, -1);
            //删除 缓存
            Boolean delete = redisTemplate.delete(key);
            //存入数据库
            chatMessageService.insertChatMessage(range);
        }
    }

    /**
     * 删除缓存在redis中的
     */
    @Scheduled(fixedRate = 1000*60*60*6)
    public void delWsTask(){
        Set<String> keys = redisTemplate.keys("websocket_show*");
        redisTemplate.delete(keys);
    }
}
